//
//  SYUploadImageNetworking.m
//  YHApp
//
//  Created by -- on 2021/7/23.
//

#import "SYUploadImageNetworking.h"

@implementation SYUploadImageNetworking

+ (SYUploadImageNetworking *)shareSingle
{
    static dispatch_once_t onceToken;
    static SYUploadImageNetworking *rq;
    dispatch_once(&onceToken, ^{
        rq = [[SYUploadImageNetworking alloc] init];
    });
    return rq;
}

- (void)initUploadImageUrl:(NSString*)url param:(id)param image:(UIImage *)image successBlock:(uploadImageSuccessBlock)successBlock failureBlock:(uploadImageFailureBlock)failureBlock progressBlock:(uploadImageProgress)progressBlock {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    
    NSString *Url = [NSString stringWithFormat:@"%@%@",kHaBaseUrl,url];
    
//    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
//    [request setValue:HAUserDefaults.token forHTTPHeaderField:@"token"];

    __block uploadImageSuccessBlock success = successBlock;
    __block uploadImageFailureBlock failure = failureBlock;
    __block uploadImageProgress progress = progressBlock;
    
    [manager POST:Url parameters:param headers:@{@"token":HAUserDefaults.token} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (image) {
            
            NSData *imageData = UIImageJPEGRepresentation(image, 0.25);
            
            // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
            // 要解决此问题，
            // 可以在上传时使用当前的系统事件作为文件名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
            /*
             *该方法的参数
             1. appendPartWithFileData：要上传的照片[二进制流]
             2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
             3. fileName：要保存在服务器上的文件名
             4. mimeType：上传的文件的类型
             */
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"]; //
            
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        ino64_t total = uploadProgress.totalUnitCount;
        ino64_t complete = uploadProgress.completedUnitCount;
        double p = complete/total;
        if (progress) {
            progress(p);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SYDataModel *responseModel = [SYDataModel mj_objectWithKeyValues:responseObject];
        if (success) {
            success(responseModel);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

- (void)uploadDataGETUrl:(NSString*)url param:(id)param successBlock:(uploadImageSuccessBlock)successBlock failureBlock:(uploadImageFailureBlock)failureBlock {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    __block uploadImageSuccessBlock success = successBlock;
    __block uploadImageFailureBlock failure = failureBlock;
    [manager POST:url parameters:param headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SYDataModel *responseModel = [SYDataModel mj_objectWithKeyValues:responseObject];
        if (success) {
            success(responseModel);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}


@end
